package wec_wallet.ebo.com.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.application.Phone;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import bassproject.ebo.com.ebobass.utils.IFileUtil;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.Lg;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.common.Constant;
import wec_wallet.ebo.com.common.HttpUtils;
import wec_wallet.ebo.com.util.PermissionsChecker;
import wec_wallet.ebo.com.util.StringUtil;
import wec_wallet.ebo.com.utils.Functions;

/**
 * 举报主界面
 * Created by Administrator on 2018/3/9.
 */

public class ReportActivity extends MyBaseActivity implements View.OnClickListener {
    Spinner sp;
    @BindView(R.id.img_report_pic)
    ImageView img_pic;
    IHttpPostListener phoneListener = new IHttpPostListener() {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (!TextUtils.isEmpty(result)) {
                JSONObject resultObject = null;
                try {
                    resultObject = new JSONObject(result);
                    String error = resultObject.getString("error");
                    if (resultObject.has("is_auth") && (resultObject.getString("is_auth")).equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(ReportActivity.this);//登录过期

                        return;
                    }
                    if (resultObject.has("error_msg")) {
                        IToast.show(resultObject.getString("error_msg"));
                        return;
                    }
                    if (error.equals("0")) {
                        JSONArray data = resultObject.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            Phone phone = new Phone();
                            phone.setPhone(data.getString(i));
                            Phone.insertdata(phone);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private RelativeLayout re_back;
    private Button btn_upload, btn_submit;
    private TextView tv_fileName;
    private EditText et_name, et_cardId, et_phone, et_other;
    private String result;
    private String name, path, gender = "0";
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 110:
                    //判断网络是否连接
                    IToast.show(getString(R.string.isConnect));
                    break;
                case 101:
                    //系统异常
                    IToast.show(getString(R.string.system_exception));
                    break;
                case 3:
                    //文件上传
                    JSONObject resultObject;
                    try {
                        resultObject = new JSONObject(result);
                        String status = resultObject.getString("error");
                        if (resultObject.has("is_auth") && resultObject.getString("is_auth").equals
                                ("0")) {
                            IToast.show(resultObject.getString("error_msg"));
                            Functions.relogin(ReportActivity.this);//登录过期

                            return;
                        }
                        if (resultObject.has("error_msg")) {
                            IToast.show(resultObject.getString("error_msg"));
                            return;
                        }
                        if (status.equals("0")) {
                            JSONArray dataObject = new JSONArray(resultObject.getString("data"));
                            JSONObject string = (JSONObject) dataObject.get(0);
                            JSONObject extra = string.getJSONObject("extra");
                            path = extra.getString("path");
                            name = extra.getString("name");

                            tv_fileName.setText(name);
                            IToast.show(getString(R.string.upload_success));
                        } else {
                            IToast.show(getString(R.string.upload_error));

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


            }
        }
    };
    private String[] mStringArray;
    private ArrayAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report);
        ButterKnife.bind(this);
        tv_fileName = (TextView) findViewById(R.id.tv_report_file);
        et_name = (EditText) findViewById(R.id.et_report_name);
        et_cardId = (EditText) findViewById(R.id.et_report_cardId);
        et_phone = (EditText) findViewById(R.id.et_report_phone);
        et_other = (EditText) findViewById(R.id.et_report_other);
        mStringArray = getResources().getStringArray(R.array.spinnerData);
        sp = (Spinner) findViewById(R.id.et_report_gender);

        adapter = ArrayAdapter.createFromResource(this, R.array.spinnerData, R.layout
                .activity_spinner_item);
        adapter.setDropDownViewResource(R.layout.activity_spinner_dropdown_stytle);

        //将adapter2 添加到spinner中
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (mStringArray[i].equals(getString(R.string.report_male))) {
                    gender = "2";
                }
                if (mStringArray[i].equals(getString(R.string.report_female))) {
                    gender = "1";
                }
                if (mStringArray[i].equals(getString(R.string.report_gender_no))) {
                    gender = "0";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        btn_submit = (Button) findViewById(R.id.btn_report_submit);
        btn_submit.setOnClickListener(this);
        re_back = (RelativeLayout) findViewById(R.id.actionbar_back);
        re_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btn_upload = (Button) findViewById(R.id.btn_report);
        btn_upload.setOnClickListener(this);
    }

    @Override
    public void initViews() {

    }

    private void getReport() {
        if (isEmpty()) {
            Map<String, Object> map = new HashMap<>();
            if (!StringUtil.isStringEmpty(et_cardId.getText().toString())) {
                map.put("idcard", et_cardId.getText().toString());
            }
            if (!StringUtil.isStringEmpty(et_phone.getText().toString())) {
                map.put("mobile", et_phone.getText().toString());
            }
            if (!StringUtil.isStringEmpty(et_name.getText().toString())) {
                map.put("name", et_name.getText().toString());
            }
            if (!StringUtil.isStringEmpty(et_other.getText().toString())) {
                map.put("other_contact", et_other.getText().toString());
            }
            if (!StringUtil.isStringEmpty(name)) {
                map.put("thumb", name);
            }
            if (!StringUtil.isStringEmpty(path)) {
                map.put("thumb_path", path);
            }
            map.put("sex", gender);
            map.put("token", I_Share.readAccountToken());
            map.put("uid", I_Share.readAccountUserid());
//        map.put("remarks", "");
//        map.put("transfer_address", "");
            Functions.post(ReportActivity.this, Constant.URL_REPORT, map, new
                    ListenerReport(), false, true);
        } else {
            IToast.show(getString(R.string.not_empty));
        }
    }

    private boolean isEmpty() {
        String cadId = et_cardId.getText().toString();
        String phone = et_phone.getText().toString();
        String names = et_name.getText().toString();
        String other = et_other.getText().toString();
        if (!StringUtil.isStringEmpty(cadId)
                || !StringUtil.isStringEmpty(phone)
                || !StringUtil.isStringEmpty(name)
                || !StringUtil.isStringEmpty(names)
                || !StringUtil.isStringEmpty(path)
                || !StringUtil.isStringEmpty(other)
                ) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_report_submit:
                getReport();
                break;
            case R.id.btn_report:
                String[] primissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
                if (PermissionsChecker.lacksPermissions(this, primissions)) {
                    PermissionsChecker.showMissingPermissionDialog(this, 2100,
                            getString(R.string.dialog_title), getString(R.string.dialog_msg),
                            primissions);
                } else {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(intent, 100);
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2100) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, 100);
        }
    }

    private void getPhone() {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("id", "1");
        Functions.post(this,Constant.URL_GETPHONE, postParams, phoneListener, false, false);
    }

    //选择文件后添加上传任务
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            Lg.d("未选择上传文件！");
            return;
        }
        Uri Uri_UploadFile = data.getData();
        String fileName = IFileUtil.getFileAbsolutePath(this, Uri_UploadFile);
        switch (requestCode) {
            case 100:
                showNormalDialog(fileName);
                Bitmap bitmap = BitmapFactory.decodeFile(fileName);
                if (bitmap != null) {
                    img_pic.setImageBitmap(bitmap);
                }
                break;
        }
    }

    private void showNormalDialog(final String fileName) {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(ReportActivity.this);
        normalDialog.setTitle("提示");
        normalDialog.setMessage("是否上传文件?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        getUploadFile(fileName);
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }

    private void getUploadFile(String fileName) {
        if (!StringUtil.isConnect(getApplicationContext())) {
            handler.sendEmptyMessage(110);

            return;
        }
        Map<String, String> maps = new HashMap<>();
        maps.put("uid", I_Share.readAccountUserid());
        maps.put("token", I_Share.readAccountToken());

        try {
            HttpUtils.uploadFile(Constant.URL_UPLOAD, "thumb", fileName, maps, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    handler.sendEmptyMessage(101);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    result = response.body().string();
                    if (response.isSuccessful()) {
                        handler.sendEmptyMessage(3);

                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ListenerReport implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    String status = resultObject.getString("error");
                    if (resultObject.has("is_auth") && resultObject.getString("is_auth").equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(ReportActivity.this);//登录过期
                        return;
                    }
                    if (resultObject.has("error_msg")) {
                        IToast.show(resultObject.getString("error_msg"));
                        return;
                    }
                    if (status.equals("0")) {
                        IToast.show(getString(R.string.report_success));
                        et_cardId.setText("");
                        et_name.setText("");
                        et_other.setText("");
                        et_phone.setText("");
                        img_pic.setImageDrawable(null);
                        name = "";
                        path = "";
                        tv_fileName.setText("");
                        getPhone();
                    } else {
                        IToast.show(getString(R.string.report_error));

                    }

                } catch (Exception e) {
                    // TODO: handle exception
//                    IToast.show(e.toString());
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            } else {
                Lg.d("黑名单列表 result=null");

            }
        }
    }
}


